package com.zp.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录拦截器
 */
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();

        String loginUrl = httpRequest.getContextPath() + "/login.html";
        String url = httpRequest.getRequestURI();

        int idx = url.lastIndexOf("/");
        String endWith = url.substring(idx + 1);

        if (!endWith.equals("login.html") && !endWith.equals("register.html")) {
            // 不是登录或者注册页面

            if (!isLogin(httpRequest)) {
                (httpResponse).sendRedirect("login.html");
            } else {
                filterChain.doFilter(request, response);
            }
        } else {
            filterChain.doFilter(request, response);
        }

        // 在 patternURL中的都不拦截
    }

    private boolean isLogin(HttpServletRequest request) {
        HttpSession session = request.getSession();

        if (session.getAttribute("CURRENT_USER") != null) {
            return true;
        }
        else {
            return false;
        }
    }

    @Override
    public void destroy() {

    }
}
